package com.sziit.se.highconcurrency.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadExecutorConfig {

    /**
     * 核心线程数
     */
    @Value("${thread.core_pool_size}")
    private int corePoolSize;

    /**
     * 最大线程数
     */
    @Value("${thread.max_pool_size}")
    private int maxPoolSize;

    /**
     * 队列数
     */
    @Value("${thread.queue_capacity}")
    private int queueCapacity;

    /**
     * 线程名称前缀
     */
    @Value("${thread.name_prefix}")
    private String namePrefix;

    /**
     * 非核心线程存活时间
     */
    @Value("${thread.keep_alive_seconds}")
    private int keepAliveSeconds;

    /**
     * 设置任务最大等待时长
     */
    @Value("${thread.await_termination_seconds}")
    private int awaitTerminationSeconds;


    @Bean
    public ExecutorService threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(namePrefix);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor.getThreadPoolExecutor();
    }
}